/**
 * Description:
 *
 * @author      Eden
 * @datetime    2017/1/2 01:18
 * @copyright   WuHan HuQi Technology Co.,Ltd.
 * @url         http://cnhuqi.com
 */

(function () {

    "use strict";


    var popup = new auiPopup();
    var api = {
        'getDetail': '/api/goods/getGoodsDetail',
        'addToCar': '/api/car/add',
        'getCounter': '/api/car/counter',
        'collectUrl': '/api/collect/doCollect'
    };
    sm.controller('wx-goods-detail-controller', ['$scope', '$http', '$sce', 'Modal', 'Toast', function ($scope, $http, $sce, Modal, Toast) {

        $scope.detail = {};
        $scope.stars = [];
        $scope.related = [];
        $scope.goodsNum = 1;
        $scope.carCounter = 0;
        $scope.topPrice = '';
        $scope.selectedItem = {};
        $scope.alertType = 'car';
        $scope.comments = [];

        $scope.minPrice = 0;
        $scope.maxPrice = 0;
        $scope.minOldPrice = 0;
        $scope.maxOldPrice = 0;

        $scope.topPriceShow = 0;
        $scope.topOldPriceShow = 0;

        var goodsId = GetQueryString('id');
        $scope.getGoodsDetail = function () {
            $http.get(api.getDetail, {
                params: {
                    'goodsId': goodsId
                }
            }).success(function (res) {
                if (res.state) {
                    $scope.detail = angular.extend($scope.detail, res.data);
                    for(var i = 0; i < res.data.stars; i++) {
                        $scope.stars[i] = i + 1;
                    }
                    $scope.trustHtml = $sce.trustAsHtml($scope.detail.content);
                    $scope.related = res.data.related.data;

                    if (res.data.minPrice != 0 && res.data.maxPrice != 0 && res.data.minPrice == res.data.maxPrice) {
                        $scope.topPrice = '￥' + res.data.minPrice;
                    } else if (res.data.minPrice != 0 && res.data.maxPrice != 0 && res.data.minPrice != res.data.maxPrice) {
                        $scope.topPrice = '￥' + res.data.minPrice + '~￥' + res.data.maxPrice;
                    } else {
                        $scope.topPrice = '￥' + res.data.price;
                    }

                    // selected
                    $scope.detail.rules[0].selected = true;
                    $scope.selectedItem = $scope.detail.rules[0];

                    $scope.comments = res.comments;
                    calcPrice();
                    sliders(res.data.thumbs);
                    share();
                }
            });
        };
        $scope.getGoodsDetail();

        function calcPrice ()
        {
            if (!$scope.detail.rules.length) {
                return false;
            }

            var sale = [], old = [];
            angular.forEach($scope.detail.rules, function (val, key) {
                old.push(val.oldPrice);     // 原价
                sale.push(val.salePrice);    // 售价
            });

            $scope.minPrice = (Math.min(sale) / 100).toFixed(2);
            $scope.maxPrice = (Math.max(sale) / 100).toFixed(2);

            console.log($scope.minPrice, $scope.maxPrice)

            if ($scope.minPrice != $scope.maxPrice) {
                $scope.topPriceShow = $scope.minPrice + ' - ' + $scope.maxPrice;
            } else {
                $scope.topPriceShow = $scope.minPrice;
            }

            $scope.minOldPrice = (Math.min(old) / 100).toFixed(2);
            $scope.maxOldPrice = (Math.max(old) / 100).toFixed(2);

            if ($scope.minOldPrice != $scope.maxOldPrice) {
                $scope.topOldPriceShow = $scope.minOldPrice + ' - ' + $scope.maxOldPrice;
            } else {
                $scope.topOldPriceShow = $scope.minOldPrice;
            }
        }

        $scope.selectedRule = function (index) {
            angular.forEach($scope.detail.rules, function (val) {
                val['selected'] = false;
            });
            $scope.detail.rules[index].selected = true;
            $scope.selectedItem = $scope.detail.rules[index];
        };

        // 跳转直播页面
        $scope.gotoVideo = function () {
            if (!$scope.detail.liveUrl) {
                return false;
            }
            location.href = $scope.detail.liveUrl;
        };

        // 幻灯片
        function sliders(thumbs) {

            var numbers = thumbs.length;
            var html = '';
            for (var i = 0; i < numbers; i++) {
                html += '<div class="aui-slide-node aui-slide-node-middle aui-slide-node-center">'
                    + '<div class="aui-content aui-padded-15">'
                    + '<img src="'+ thumbs[i]['thumb_view'] +'" alt="">'
                    + '</div>'
                    + '</div>';
            }

            $('#slider-box').html(html);
            setTimeout(function () {
                var slide2 = new auiSlide({
                    container:document.getElementById("aui-slide2"),
                    "speed":300,
                    "autoPlay": 1, //自动播放
                    "pageShow":true,
                    "loop":true,
                    "pageStyle":'dot',
                    'dotPosition':'center'
                });
            });
        }

        function share() {
            wx.onMenuShareTimeline({
                title: $scope.detail.goodsName, // 分享标题
                link: $scope.detail.shareUrl, // 分享链接
                imgUrl: $scope.detail.thumb, // 分享图标
                success: function () {
                    // 用户确认分享后执行的回调函数
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                }
            });

            wx.onMenuShareAppMessage({
                title: $scope.detail.goodsName, // 分享标题
                desc: $scope.detail.description || $scope.detail.goodsName, // 分享描述
                link: $scope.detail.shareUrl, // 分享链接
                imgUrl: $scope.detail.thumb, // 分享图标
                type: '', // 分享类型,music、video或link，不填默认为link
                dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                success: function () {
                    // 用户确认分享后执行的回调函数
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                }
            });
        }

        $http.get(api.getCounter).success(function (res) {
            if (res.state) {
                $scope.carCounter = res.data.total;
            }
        });

        $scope.collect = function () {
            if (!goodsId) {
                return false;
            }

            var status = $scope.detail.collected ? 1 : 0;
            var newStatus = status ? 0 : 1;
            $http.post(api.collectUrl, {
                goodsId: goodsId,
                action: newStatus ? 'on' : 'off'
            }).success(function (res){
                if (res.state) {
                    if (newStatus) {
                        Toast.success({title: '收藏成功'});
                    } else {
                        Toast.success({title: '移除成功'});
                    }
                    $scope.detail.collected = newStatus;
                } else {
                    Toast.error({
                        title: '收藏失败'
                    });
                }
            });
        };

        // 立即购买
        $scope.buyNow = function () {
            if (!$scope.goodsNum || !goodsId) {
                Toast.error({title: "请选择商品"});
            }

            Modal.alert({
                title: '操作提示',
                content: '您确定立即购买此商品吗?',
                buttons: [{
                    name: '再逛逛'
                }, {
                    name: '立即购买',
                    event: function () {
                        doAddToCar('buy');
                    }
                }]
            });
        };

        function doAddToCar(type) {
            $http.post(api.addToCar, {
                num: $scope.goodsNum,
                goodsId: goodsId,
                ruleId: $scope.selectedItem.id,
                type: type == 'buy' ? 'buy' : null
            }).success(function (res) {
                if (res.state) {

                    if (type == 'buy') {
                        location.href = '/order/confirm';
                    } else {
                        Modal.alert({
                            title: '成功提示',
                            content: "商品添加成功",
                            buttons:[{
                                name: '再逛逛',
                                event: function () {
                                    // 修改购物车数量
                                    location.href = '';
                                }
                            }, {
                                name: '前往购物车',
                                event: function () {
                                    location.href = '/car';
                                }
                            }]
                        });
                    }
                } else {
                    if (type == 'buy') {
                        var error = res.error ? res.error : '下单失败';
                    } else {
                        var error = res.error ? res.error : '添加失败';
                    }
                    Toast.error({title: error});
                }
            });
        }

        // 加入购物车
        $scope.addToCar = function (){

            if (!$scope.goodsNum || !goodsId) {
                Toast.error({title: "请选择商品"});
            }

            doAddToCar();
        };


        $scope.num = function (type) {
            // 加
            if (type == 'up') {
                if ($scope.goodsNum >= $scope.detail.stock) {
                    Toast.error({title: "商品数量不足"});
                } else {
                    $scope.goodsNum += 1;
                }
            }
            // 减
            else {
                $scope.goodsNum = $scope.goodsNum <= 1 ? 1 : $scope.goodsNum - 1;
            }
        };


        $scope.alertAddCar = function () {
            $scope.alertType = 'car';
            popup.show(document.getElementById("bottom"))
        };

        $scope.alertBuyNow = function () {
            $scope.alertType = 'buy';
            popup.show(document.getElementById("bottom"))
        };

        $scope.gotoBase = function () {
            var baseId = $scope.detail.baseId;
            location.href = '/base?baseId=' + baseId;
        };

        $scope.hidePop = function () {
            popup.hide();
        };

    }]);

})();